package com.kcsoft.service.impl;

import com.kcsoft.mapper.KeyWordMapper;
import com.kcsoft.pojo.KeyAll;
import com.kcsoft.pojo.KeyTotal;
import com.kcsoft.pojo.KeyWord;
import com.kcsoft.pojo.Result;
import com.kcsoft.service.KeyWordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class KeyWordServiceImpl implements KeyWordService {

    @Autowired
    KeyWordMapper keyWordMapper;

    @Scheduled(cron = "0 0 0 * * ?")
    public void getKeyWordTotal() {

        LocalDate yesterday = LocalDate.now().minusDays(1);
        LocalDateTime startOfDay = yesterday.atStartOfDay();
        LocalDateTime endOfDay = yesterday.atTime(LocalTime.MAX);

        List<KeyWord> keyWords = keyWordMapper.getKeyWords(startOfDay, endOfDay);

        Map<String, Long> results = keyWords.stream()
                .collect(Collectors.groupingBy(KeyWord::getKeyWord, Collectors.counting()));

        results.forEach((key, value) -> {
            KeyTotal res = new KeyTotal();
            res.setKeyWord(key);
            res.setTotal(value.intValue());
            res.setCreateTime(yesterday);
            keyWordMapper.saveKeyTotal(res);
        });
    }

    @Override
    public List<KeyTotal> getKeyTotals(LocalDate date) {
        return keyWordMapper.getTotal(date);
    }

    @Override
    public void saveKey(String key) {
        keyWordMapper.saveKey(key);
    }

    @Override
    public List<KeyAll> getAll() {
        return keyWordMapper.getAll();
    }
}
